<?php

namespace app\common\model;

use basic\ModelBasic;
use think\Cache;

class Area extends ModelBasic
{
	use \traits\ModelTrait;

    public static function toTree ()
    {
        $area_cache_key = '_AREA_TREE_CACHE_';
        $area_tree      = Cache::get($area_cache_key);

        if ( empty($area_tree) ) {
            $area_tree = self::field('area_code as value,area_name as label,id')->where(['pid'=>0,'level' => 0])->order('area_code asc')->select()->toArray();
            foreach ( $area_tree as &$province ) {
                $province['children'] = self::field('area_code as value,area_name as label,id')->where(['pid'=>$province['id'],'level' => 1])->order('area_code asc')->select()->toArray();

                foreach ( $province['children'] as &$city ) {
                    $city['children'] = self::field('area_code as value,area_name as label,pid,id')->where(['pid'=>$city['id'],'level' => 2])->order('area_code asc')->select()->toArray();
                }
            }
            //Cache::set($area_cache_key , $area_tree , 86400 * 30);
        }

        return $area_tree;
    }
} //Class End
